<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 区域管理 </span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleForm({})" v-auth="'unitmanage:unitRegion:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ tid: record.tid })">
          {{ record.name }}
        </a>
      </template>
      <!-- 新增 action 插槽 -->
      <template #action="{ record }">
        <a-button @click="handleForm({ tid: record.tid })" v-auth="'unitmanage:unitRegion:edit'" type="text">
          <span style="font-size:14px; color: #52c41a;">编辑</span>
        </a-button>
        <a-button @click="handleFormDetail({ tid: record.tid })"  type="text">
          <span style="font-size: 14px; color: #4169E1;">详情</span>
        </a-button>
        <Popconfirm
          title="是否确认删除区域信息表"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete(record)"
          @cancel="handleCancel"
        >
          <a-button v-auth="'unitmanage:unitRegion:edit'" type="text" style="color: red;">
            <span style="font-size: 14px;">删除</span>
          </a-button>
        </Popconfirm>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormDeatil @register="registerDrawerDetail" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="ViewsUnitmanageUnitRegionList">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { unitRegionDelete, unitRegionListData } from '/@/api/unitmanage/unitRegion';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { unitBuildingListData } from '/@/api/unitmanage/unitBuilding';
  import InputForm from './form.vue';
  import FormDeatil from './formDetail.vue';
  import { UnitRegion } from '@/api/unitmange/unitRegion';
  import { officeTreeData } from '/@/api/sys/office';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { Popconfirm } from 'ant-design-vue'; // 引入 Popconfirm 组件

  const { t } = useI18n('unitmanage.unitRegion');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('区域信息表管理'),
  };

  const allPeripheryOptions = ref<UnitRegion[]>([]);
  const regionName = ref('');
  const buildingName = ref('');
  const regionParams = computed(() => {
    return {
      name: regionName.value,
    };
  });
  const buildParams = computed(() => {
    return {
      name: buildingName.value,
    };
  });

  const EnterpriseParams = ref<Recordable>({
    name: '',
  });

  const searchForm: FormProps = {
    baseColProps: { md: 8, lg: 6 },
    labelWidth: 90,
    schemas: [
      {
        label: t(''),
        field: 'id',
        fieldLabel: 'name',
        component: 'TreeSelect',
        componentProps: {
          placeholder: t('请输入区域名称'),
          api: unitRegionListData,
          resultField: 'list',
          fieldNames: { label: 'name', value: 'id' },
          params: regionParams,
          allowClear: true,
          immediate: false,
          each: false,
          showSelect: true,
          optionFilterProp: 'label',
          showSearch: true,
          onSearch: (value) => {
            regionName.value = value;
            // reload();
          },
        },
      },
      {
        label: t(''),
        field: 'unitCode',
        fieldLabel: 'enterpriseName',
        component: 'Select',
        componentProps: () => {
          return {
            placeholder: t('请输入所属主体'),
            api: unitEnterpriseDominantListData,
            params: EnterpriseParams.value,
            fieldNames: { label: 'name', value: 'unitCode' },
            resultField: 'list',
            notFoundContent: '未查询到记录',
            filterTreeNode: false,
            allowClear: true,
            filterOption: false,
            immediate: true,
            onSearch: (value: string) => {
              EnterpriseParams.value.name = value;
              console.log(EnterpriseParams.value);
            },
          };
        },
      },
      {
        label: t(''),
        field: 'buildName',
        fieldLabel: 'buildName',
        component: 'TreeSelect',
        componentProps: {
          placeholder: t('请输入建筑名称'),
          api: unitBuildingListData,
          params: buildParams,
          resultField: 'list',
          fieldNames: { label: 'name', value: 'name' },
          allowClear: true,
          immediate: false,
          each: false,
          showSelect: true,
          optionFilterProp: 'label',
          showSearch: true,
          onSearch: (value) => {
            buildingName.value = value;
            reload();
          },
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('区域名称'),
      dataIndex: 'name',
      key: 'a.name',
      sorter: true,
      width: 230,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('主体名称'),
      dataIndex: 'enterpriseName',
      key: 'a.enterprise_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('建筑名称'),
      dataIndex: 'buildName',
      key: 'a.build_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('楼层数'),
      dataIndex: 'floorNum',
      key: 'a.floor_num',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('详细地址'),
      dataIndex: 'address',
      key: 'a.address',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('周边区域'),
      dataIndex: 'master',
      key: 'a.master',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('设备数量'),
      dataIndex: 'equNumber',
      key: 'a.equ_number',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('操作人'),
      dataIndex: 'operator',
      key: 'a.operator',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      width: 160,
      fixed: 'right',
      slot: 'action' // 指定使用 action 插槽
    }
  ];

  const [registerTable, { reload }] = useTable({
    api: unitRegionListData,
    beforeFetch: async (params) => {
      const route = unref(router.currentRoute);
      const unitCode = route.query.unitCode;
      if (unitCode) {
        params.unitCode = unitCode;
      }
      // try {
      //   // 获取所有联动区域列表
      //   const res = await unitRegionListData({});
      //   allPeripheryOptions.value = res.list || [];
      // } catch (error) {
      //   console.error('获取联动区域列表失败:', error);
      // }
      return params;
    },
    columns: tableColumns,
    // actionColumn: actionColumn, // 移除原有的 actionColumn 配置
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawerDetail, { openDrawer: openDrawerDetail }] = useDrawer();

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }
  function handleFormDetail(record: Recordable) {
    openDrawerDetail(true, record);
  }

  async function handleDelete(record: Recordable) {
    const params = { tid: record.tid };
    const res = await unitRegionDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  function handleCancel() {
    console.log('取消删除操作');
  }
</script>